package com.lwei.tallybook.client.config;

import com.lwei.tallybook.base.domain.Account;
import com.lwei.tallybook.service.service.AccountService;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

/**
 * 自定义认证器
 * @author sks.lwei
 */
@Log4j2
public class ShiroRealm extends AuthorizingRealm {

    @Resource
    private AccountService accountService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确
     * 2分钟内不会重复执行该方法
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token){
        //获取用户的输入的账号.
        String username = (String)token.getPrincipal();
        //通过username从数据库中查找 User对象，如果找到，没找到.
        Account account = accountService.getAccountByUuid(username);

        if(account == null){
            log.warn("----->账户不存在[{}]", username);
            throw new UnknownAccountException();
        }

        String password = account.getPassWord();

        //做密码验证
        return new SimpleAuthenticationInfo(account, password, super.getName());
    }

}
